import Request from './../../libs/luch-request/index.js';
import toast from './../../libs/toast';
import * as query from './../../libs/query';
import * as c from './config';
import * as h5Config from './config/h5.js';

const http = new Request({
	baseURL : c.baseURL
});
// 请求拦截
http.interceptors.request.use((config) => {
	//加载中内容
	toast.loading(config?.custom?.loading);
	//添加头部的header
	config.header.Authorization = getAuthorization();
	//data的格式化
	config.data = config.data || {};
	return config;
}, config => {
	toast.unloading();
	return Promise.reject(config)
});
// 响应拦截
http.interceptors.response.use((sus) => {
	toast.unloading();
	if (sus?.data?.code == 200) {
		toast.success(sus?.data?.message,sus?.config?.custom?.susToast);
		return sus?.data === undefined ? {} : sus?.data
	}else if(sus?.data?.code == 501){
		//前往登录页
		toLogin();
		return Promise.reject(sus?.data);
	}else{
		toast.error(sus?.data?.message,sus?.config?.custom?.errToast);
		return Promise.reject(sus?.data);
	}
}, (response) => { 
	toast.unloading();
	toast.error(`statusCode:${response.statusCode}`);
	return Promise.reject(response)
})





function toLogin(){
	// #ifdef H5
		let oauthURL = query.build(h5Config?.attachData,h5Config?.path,c?.baseURL);
		let className= h5Config?.className;
		let title    = h5Config?.title;
		let content  = h5Config?.content;
		let confirmColor = h5Config?.confirmColor;
		uni.showModal({
			class:className,
			title: title,
			content: content,
			showCancel:false,
			confirmColor:confirmColor,
			success: function (res) {
				if (res.confirm) {
					location.replace(oauthURL);
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	// #endif
}




function getAuthorization(){
	var Authorization = {};
		Authorization.token = getToken();
	// 登录token
	if(typeof Authorization.token == 'string' && Authorization.token.length>0){
	}else{ delete Authorization.token; }
	// 设置appid
	// #ifdef MP-WEIXIN
		Authorization.appId = uni.getAccountInfoSync().miniProgram.appId;
	// #endif
	// #ifdef H5
		Authorization.appId = window.location.origin;
	// #endif
	// #ifdef MP-TOUTIAO
		Authorization.appId = uni.getEnvInfoSync().microapp.appId
	// #endif
	return JSON.stringify(Authorization);
}
function getToken(){
	// #ifdef H5
		var url = location.href;
		var reg = new RegExp("#"+c.LOGINKEY+"=([a-zA-Z0-9:_^#]*)$");
		var matches = url.match(reg);
		if(matches&&matches[1]&&(matches[1].length>0)){
			uni.setStorageSync(c.LOGINKEY,matches[1]);
		}
	// #endif
	return uni.getStorageSync(c.LOGINKEY);
}

export default http;